package com.abaddon.view;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.abaddon.model.TagManager;

public class SettingsView extends Activity{
	private EditText nameField = null;
	private CheckBox displayLocation;
	private EditText serverAdressField = null;
	private EditText serverPortField = null;
	private Button categoriesButton;
	private List<String> allCategoriesStringList;
	private CharSequence[] allCategories;
	private boolean[] selectedCategories;
	private String oldUserName;
	private int dialogId = 0;

	@Override 
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);

		nameField = (EditText) findViewById(R.id.userName);
		displayLocation = (CheckBox) findViewById(R.id.showLocation);
		serverAdressField = (EditText) findViewById(R.id.serverAdress);
		serverPortField = (EditText) findViewById(R.id.serverPort);
		
		nameField.setText(TagManager.getAbaddonDatabase().getSetting("userName"));
		displayLocation.setChecked((TagManager.getAbaddonDatabase().getSetting("display")).equals("true"));
		serverAdressField.setText(TagManager.getAbaddonDatabase().getSetting("serverAdress"));
		serverPortField.setText(TagManager.getAbaddonDatabase().getSetting("serverPort"));
		
		oldUserName = nameField.getText().toString();
		
		//Create buttons and connect to actions
		Button okButton = (Button)findViewById(R.id.saveSettings);
		Button cancelButton = (Button)findViewById(R.id.cancelSettings);
		final Button pingServerButton = (Button) findViewById(R.id.pingServerButton);
		Button addCategoryButton = (Button) findViewById(R.id.addCategory);
		categoriesButton = (Button) findViewById(R.id.allCategories);
		updateCategories();
		final EditText newCategory = (EditText)findViewById(R.id.newCategory);
		
		addCategoryButton.setOnClickListener(new View.OnClickListener(){
			//When clicking category-button
			public void onClick(View v){
				TagManager.getAbaddonDatabase().addCategory(newCategory.getText().toString());
				updateCategories();
				newCategory.setText("");
			}
		});
		categoriesButton.setOnClickListener(new View.OnClickListener(){
			//When clicking save-button
			public void onClick(View v){
				showDialog(dialogId);
				dialogId++;
			}
		});
		okButton.setOnClickListener(new View.OnClickListener(){
			//When clicking save-button
			public void onClick(View v){
				saveSettings();
				implementSettings();

				finish();
			}
		});
		cancelButton.setOnClickListener(new View.OnClickListener(){
			//When clicking the cancel-button
			public void onClick(View v){
				finish();
			}
		});
		pingServerButton.setOnClickListener(new View.OnClickListener(){

			// Pings server to make sure it exists
			@Override
			public void onClick(View v) {
				DatagramSocket socket = null;
				DatagramPacket packet = null;
				String ping = "ping";
				try {
					socket = new DatagramSocket();
					byte[] buff = new byte[100];
					packet = new DatagramPacket(buff, buff.length, 
							InetAddress.getByName(TagManager.getServerAdress()), TagManager.getServerPort());
					packet.setData(ping.getBytes());
				} catch (SocketException e) {
					e.printStackTrace();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				try {
					socket.setSoTimeout(1000);
					socket.send(packet);
					socket.receive(packet);
					pingServerButton.setText("Server exists! Ping again?");
				} catch (SocketException e) {
					e.printStackTrace();
				} catch (IOException e) {
					pingServerButton.setText("Server doesn't exist. Ping again?");
				}

			}
		});
	}

	/**
	 * Save settings chosen by user.
	 */
	public void saveSettings(){

		//Commit values to database
		String displayLocationString = "true";
		if (displayLocation.isChecked()==false){
			displayLocationString = "false";
		}

		TagManager.getAbaddonDatabase().addSetting("userName", nameField.getText().toString());
		TagManager.getAbaddonDatabase().addSetting("display", displayLocationString);
		TagManager.getAbaddonDatabase().addSetting("serverAdress", serverAdressField.getText().toString());
		TagManager.getAbaddonDatabase().addSetting("serverPort", serverPortField.getText().toString());
		TagManager.updatePersonTitle(oldUserName, nameField.getText().toString());
	}

	/**
	 * Implement the settings chosen by user by sending the values stored
	 * in the database to TagManager.
	 */
	public void implementSettings(){
		TagManager.setServerAdress(TagManager.getAbaddonDatabase().getSetting("serverAdress"));
		TagManager.setServerPort(Integer.parseInt(TagManager.getAbaddonDatabase().getSetting("serverPort")));
		TagManager.setUserName(TagManager.getAbaddonDatabase().getSetting("userName"));
		TagManager.setSendPosition((boolean) TagManager.getAbaddonDatabase().getSetting("display").equals("true"));
	}

	/**
	 * When menu-button is clicked.
	 */
	public boolean onCreateOptionsMenu(Menu menu){
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.settings_menu, menu);
		return true;
	}

	/**
	 * Opens chosen view.
	 */
	public boolean onOptionsItemSelected(MenuItem item){
		//Handle item selection
		switch (item.getItemId()){
		case R.id.main:
			finish();
			return true;
		case R.id.help:
			startActivity(new Intent("com.abaddon.view.HELPVIEW"));
			finish();
			return true;
		case R.id.about:
			startActivity(new Intent("com.abaddon.view.ABOUTVIEW"));
			finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

    /**
     * Displays the multi-choice dialog for the categories button.
     */
	@Override
	protected Dialog onCreateDialog(int id) {
		return 
		new AlertDialog.Builder(this)
		.setTitle(R.string.placeCategories)
		.setMultiChoiceItems(allCategories, selectedCategories, new DialogInterface.OnMultiChoiceClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which, boolean isChecked) {
				
			}
		})
		.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
			//What happens when one presses delete
			@Override
			public void onClick(DialogInterface dialog, int clicked) {
				switch(clicked) {
				case DialogInterface.BUTTON_POSITIVE:
					for(int i=0; i<allCategories.length; i++){
						if(selectedCategories[i]){
							TagManager.getAbaddonDatabase().removeCategory(allCategories[i].toString());
						}
					}
					updateCategories();
					break;
				}
			}
		})
		.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			//What happens when one presses cancel
			@Override
			public void onClick(DialogInterface dialog, int clicked) {
				switch(clicked) {
				case DialogInterface.BUTTON_NEGATIVE:
					for(int i=0; i<selectedCategories.length; i++){
						selectedCategories[i] = false;
					}
					break;
				}
			}
		})
		.create();
	}
	
	/**
	 * Updates the categories button to contain all categories.
	 */
	protected void updateCategories() {
		allCategoriesStringList = TagManager.getAbaddonDatabase().getAllCategories();
		Collections.sort(allCategoriesStringList);
		Object[] objCategories = allCategoriesStringList.toArray();
		allCategories = new String[objCategories.length];
		selectedCategories = new boolean[allCategories.length];
		for (int i = 0; i<objCategories.length; i++){
			allCategories[i] = objCategories[i].toString();
		}
		String allCategoriesString = "";
		if(allCategories.length > 0){
			for(int i = 0; i < allCategories.length-1; i++) {
				allCategoriesString += allCategories[i] + ", ";
			}
			allCategoriesString += allCategories[allCategories.length-1];
		}
		else {
			allCategoriesString = "No categories";
		}
		categoriesButton.setText(allCategoriesString);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

}
